<template>
  <h1>入库页面</h1>
  <el-table :data="cangkuFenpeiList" style="width: 100%">
     <el-table-column prop="sid" label="商品编号" style="width: 180px;" />
    <el-table-column prop="cangkuNo" label="仓库编码" style="width: 100px;" />
    <el-table-column prop="cangName" label="仓库名称" style="width: 100px;"  />
    <el-table-column prop="cangKuName" label="库位名称" style="width: 100px;" />
    <el-table-column prop="chuName" label="储位名称" style="width: 100px;"  />
    <el-table-column prop="productName" label="产品名称" style="width: 100px;" />
    <el-table-column prop="productCount" label="商品数量" style="width: 180px;" />
    <el-table-column width="250"  label="出库编码">
      <template v-slot="scope">
        <div :ref="el => setBarcodeRef(el, scope.$index)" style="text-align: center; padding: 10px;">
          <!-- 条形码将在这里生成 -->
        </div>
      </template>
    </el-table-column>
  </el-table>
  
  <!-- 数字输入弹窗 -->
  <el-dialog 
    v-model="showNumberInput" 
    title="请输入数量" 
    width="400px" 
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @opened="focusNumberInput"
  >
    <el-form>
      <el-form-item label="数量:">
        <el-input-number
          ref="numberInputRef"
          v-model="inputNumber"
          :min="1"
          :max="99999"
          :precision="0"
          controls-position="right"
          style="width: 100%"
          @keyup.enter="confirmNumberInput"
          @blur="confirmNumberInput" 
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelNumberInput">取消</el-button>
        <el-button type="primary" @click="confirmNumberInput">确认</el-button>
      </span>
    </template>
  </el-dialog>
  
</template>


<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { APIs } from '../../Http/http'
import { useRoute, useRouter } from 'vue-router'
import JsBarcode from 'jsbarcode'
import globalScanner from '../../utils/globalScanner'

// 获取路由实例
const route = useRoute()
// 获取路由器实例，用于修改路由参数
const router = useRouter()

// 仓库分配列表数据
const cangkuFenpeiList = ref<any[]>([])
const currentItemIndex = ref<number>(-1)
const currentItemOriginalCount = ref<number>(0)

// 条形码生成相关
const barcodeRefs = ref<{ [key: number]: HTMLElement | null }>({})

// 数字输入弹窗相关
const showNumberInput = ref(false)
const inputNumber = ref(1) // 这个就是 Num 字段
const numberInputRef = ref()
const currentScannedItem = ref<any>(null) // 当前扫码的项目

// 初始加载数据
onMounted(() => {
  // 检查是否有路由参数，如果有则保存并清空
  const hasRouteParams = Object.keys(route.query).length > 0
  const productId = route.query.Find as string
  
  // 添加扫码回调函数，用于扫描当前列表中的条形码
  globalScanner.addCallback(handleListBarcodeScan)
  
  // 先加载基础数据
  getCangkuFenpeiList()
  
  // 如果有产品ID参数，则执行自动分配
  if (productId) {
    // 等待数据加载完成后再执行自动分配
    setTimeout(() => {
      checkAutoAllocation()
    }, 100)
  } else if (hasRouteParams) {
    // 如果有其他参数但没有产品ID，则直接清空参数
    clearRouteParams()
  }
})

// 组件卸载时移除扫码回调
onUnmounted(() => {
  globalScanner.removeCallback(handleListBarcodeScan)
})

// 处理扫描当前列表条形码的回调函数
const handleListBarcodeScan = (sid: string) => {
  console.log('扫描到的条形码:', sid)
  
  // 查找扫描的条形码是否存在于当前列表中
  const matchedItem = cangkuFenpeiList.value.find(item => item.sid === sid)
  
  if (matchedItem) {
    console.log('找到匹配的列表项:', matchedItem)
    
    // 保存当前扫码的项目信息
    currentItemIndex.value = cangkuFenpeiList.value.findIndex(item => item.sid === sid)
    currentItemOriginalCount.value = currentItemIndex.value !== -1
      ? Number(cangkuFenpeiList.value[currentItemIndex.value].productCount) || 0
      : Number(matchedItem.productCount) || 0
    currentScannedItem.value = currentItemIndex.value !== -1
      ? cangkuFenpeiList.value[currentItemIndex.value]
      : matchedItem
    
    // 重置输入数量为1
    inputNumber.value = 1
    
    // 显示数字输入弹窗
    showNumberInput.value = true
  } else {
    ElMessage.warning('未找到匹配的商品')
  }
}

// 清空路由参数的函数
const clearRouteParams = () => {
  if (Object.keys(route.query).length > 0) {
    router.replace({
      path: route.path,
      query: {}
    })
  }
}

// 获取仓库分配列表数据
const getCangkuFenpeiList = async () => {
  const response = await APIs.get('/api/Read/ShowFenPei')
  
  if (response.data.code === 100) {
    cangkuFenpeiList.value = response.data.data
    
    // 数据加载完成后，等待DOM更新然后生成所有条形码
    nextTick(() => {
      generateAllBarcodes()
    })
  }
}

// 检查URL参数是否需要自动添加
const checkAutoAllocation = () => {
  const productId = route.query.Find as string;
  const productState = parseInt(route.query.productState as string) || 1;
  const code = route.query.scanCode as string;
  const rukuNum = route.query.rukuNum;
  
  console.log('接收到的路由参数:');
  console.log('Find:', route.query.Find);
  console.log('productState:', productState);
  console.log('scanCode:', code);
  console.log('rukuNum:', rukuNum);
  
  if (productId) {
    // 传递所有必要参数，包括 rukuNum，确保类型转换
    const rukuNumValue = rukuNum ? parseInt(rukuNum as string) : 1;
    directAdd(code, rukuNumValue);
  } else {
    // 如果没有产品ID，则清空路由参数
    clearRouteParams()
  }
};

// 自动添加函数 - 添加记录
const directAdd = async (code: any, rukuNum: number) => {
    // 构建提交数据，包含产品状态、扫描码和入库数量
  const submitData: any = {
    Code: code,
    state: route.query.productState,
    count: rukuNum
  };
  
  // 打印提交的数据
  console.log('准备提交仓库分配数据:');
  console.log('产品状态(state):', submitData.state);
  console.log('扫描码(Code):', submitData.Code);
  console.log('入库数量(rukuNum):', submitData.rukuNum);
  
  // 提交数据到后端
  const response = await APIs.post('/api/Write/AddFenpeiCangku', submitData);
  
  if (response.data.code == 100) {
    ElMessage.success('入库成功');
    getCangkuFenpeiList();
  } else {
    ElMessage.error(response.data.msg)
    // 失败时清空路由参数
    clearRouteParams();
    router.push({path:"/ShenchanInfo"})
  }
}

// 条形码相关函数
const setBarcodeRef = (el: any, index: number) => {
  if (el) {
    barcodeRefs.value[index] = el as HTMLElement
  }
}

const generateBarcode = (code: string, index: number) => {
  const targetElement = barcodeRefs.value[index]
  if (targetElement && code) {
    targetElement.innerHTML = ''
    const canvas = document.createElement('canvas')
    targetElement.appendChild(canvas)
    try {
      JsBarcode(canvas, code, {
        format: "CODE128",
        width: 1.5,
        height: 60,
        displayValue: true,
        fontSize: 12,
        margin: 5
      })
    } catch (error) {
      console.error('生成条形码失败:', error)
      targetElement.innerHTML = '<span style="color: #999; font-size: 12px;">条形码生成失败</span>'
    }
  }
}

const generateAllBarcodes = () => {
  cangkuFenpeiList.value.forEach((item: any, index: number) => {
    if (item.sid) {
      setTimeout(() => {
        generateBarcode(item.sid, index)
      }, 100 * index)
    }
  })
}

// 数字输入弹窗处理函数
const focusNumberInput = () => {
  // 弹窗打开后自动聚焦到输入框
  nextTick(() => {
    if (numberInputRef.value) {
      numberInputRef.value.focus()
    }
  })
}

const cancelNumberInput = () => {
  // 取消输入，关闭弹窗
  showNumberInput.value = false
  restoreCurrentItemState()
  resetChukuState()
}

const confirmNumberInput = async () => {
  if (!currentScannedItem.value || !inputNumber.value || inputNumber.value <= 0) {
    ElMessage.warning('请输入有效的数量')
    return
  }

  const item = currentScannedItem.value
  const quantity = inputNumber.value
  const availableCount = currentItemOriginalCount.value

  if (quantity > availableCount) {
    ElMessage.warning('出库数量不能大于当前库存')
    inputNumber.value = availableCount
    return
  }

  // 关闭弹窗
  showNumberInput.value = false

  router.push({
    name: 'ChuKu',
    query: {
      productState: item.productState || 1,
      sid: item.sid,
      Num: quantity,
      item: JSON.stringify({
        code: item.sid,
        productState: item.productState || 1,
        batches: [
          {
            count: quantity,
            outNo: item.outNo || item.sid
          }
        ]
      })
    }
  })

  resetChukuState()
}

const updateCurrentItemCount = (quantity: number) => {
  if (currentItemIndex.value === -1) {
    return
  }

  const remaining = Math.max(currentItemOriginalCount.value - quantity, 0)
  const currentItem = cangkuFenpeiList.value[currentItemIndex.value]
  if (!currentItem) {
    return
  }

  const updatedItem = {
    ...currentItem,
    productCount: remaining
  }

  cangkuFenpeiList.value[currentItemIndex.value] = updatedItem
  currentScannedItem.value = updatedItem
}

watch(inputNumber, newValue => {
  if (currentItemIndex.value === -1) {
    return
  }

  const quantity = Number(newValue) || 0

  if (quantity > currentItemOriginalCount.value) {
    ElMessage.warning('出库数量不能大于当前库存')
    inputNumber.value = currentItemOriginalCount.value
    updateCurrentItemCount(currentItemOriginalCount.value)
    return
  }

  updateCurrentItemCount(quantity)
})

const resetChukuState = () => {
  currentScannedItem.value = null
  currentItemIndex.value = -1
  currentItemOriginalCount.value = 0
  inputNumber.value = 1
}

const restoreCurrentItemState = () => {
  if (currentItemIndex.value === -1) {
    return
  }

  const currentItem = cangkuFenpeiList.value[currentItemIndex.value]
  if (!currentItem) {
    return
  }

  const restoredItem = {
    ...currentItem,
    productCount: currentItemOriginalCount.value
  }

  cangkuFenpeiList.value[currentItemIndex.value] = restoredItem
  currentScannedItem.value = restoredItem
}

// 导入onUnmounted函数
import { onUnmounted } from 'vue'
</script>
